package com.business.action.platform;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import net.sf.rose.jdbc.PageBean;
import net.sf.rose.jdbc.service.Service;
import net.sf.rose.spring.ApplicationUtils;
import net.sf.rose.util.BeanWrapper;
import net.sf.rose.util.ClassUtils;
import net.sf.rose.util.DataUtils;
import net.sf.rose.web.util.ClassUtil;

/**
 * 
 * @author fengjian
 * @version 创建时间：2018年7月15日
 * 复杂的后台操作接口调用类
 */
@Controller
@RequestMapping("/com")
public class CustomAction {

    /**
     * 服务调用
     */
	@ResponseBody
	@RequestMapping("/service.do")
	public PageBean service(HttpServletRequest request, Service service, String serviceID, String methodName) {
		PageBean page = new PageBean();
		// 根据serviceID从Spring容器中获取注入的服务对象
		Object obj = ApplicationUtils.getApplicationContext().getBean(serviceID);
		// 组织对象方法调用的参数
		List<String[]> list = ClassUtil.getParamterDefine(obj.getClass(), methodName);
		Object[] args = new Object[list.size()];
		for (int i = 0; i < args.length; i++) {
			String[] arr = list.get(i);
			// 如果是Java基础类型
			if (arr[1].startsWith("java.")) {
				String val = request.getParameter(arr[0]);
				if (val != null) {
					args[i] = DataUtils.convertValue(arr[1], val);
				}
			} else if (arr[1].equals("javax.servlet.http.HttpServletRequest")) {
				args[i] = request;
			} else if (arr[1].equals(Service.class.getName())) {
				args[i] = service;
			} else if (arr[1].equals(PageBean.class.getName())) {
				args[i] = page;
			}
			// 如果是实体对象基础类型
			else {
				Object object = DataUtils.getInstance(arr[1]);
				BeanWrapper bw = new BeanWrapper(object);
				for (String name : bw.getAllFieldNames()) {
					String val = request.getParameter(name);
					if (val != null && !val.trim().equals("")) {
						bw.set(name, val);
					}
				}
				args[i] = object;
			}
		}
		// 执行对象的方法
		ClassUtils.execute(obj, methodName, args);
		return page;
	}

}
